<!--
 * @Description: 告警模板配置
-->
<template>

  <MainSlot>
    <template v-slot:searchForm>
      <!-- <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm> -->
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <el-table ref="tableData" v-loading="loading" :data="tableData" stripe border @row-click="handleEdit"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="templateName" label="模板名称" />
        <el-table-column prop="dataTypeName" label="数据类别" />
        <el-table-column prop="sendingInterval" label="发送间隔" />
        <el-table-column prop="filterType" label="滤波类型" />
        <el-table-column prop="filterValue" label="滤波值" />
        <el-table-column width="200" label="操作">
          <template v-if="scope.row.alarmTemplateId" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" size="small" @click="dialogeSeeFormVisible = true">
              <i class="el-icon-view"></i> 查看
            </el-button>
            <!--  -->
            <el-button class="text-btn-cursor" type="text" size="small" v-if="judgePermission(20, 'edit')"
              @click="editData(scope.row)">
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button class="text-btn-cursor cursor-delete" type="text" size="small"
              v-if="judgePermission(20, 'delete')" @click="handleDelete(scope.row)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="changeCurrentPage" :page="currentPage" :size="pageSize" :total="totalSize">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal='false' :title="titleText + '告警模板信息'" :visible.sync="dialogFormVisible"
        :before-close="cancel" width="50%">
        <el-form ref="formData" :model="formData" :rules="rules" label-width="120px" class="demo-ruleForm">
          <el-form-item label="模板名称" prop="templateName">
            <el-input v-model="formData.templateName" clearable placeholder="请输入模板名称" />
          </el-form-item>
          <el-form-item label="数据类型" prop="dataTypeName">
            <el-select class="w100p" filterable clearable v-model="formData.dataTypeName"
              :placeholder="formData.dataTypeName" @change="addDataType">
              <el-option v-for="(item, index) in dataTypeList" :key="index"
                :value="{ value: item.dataTypeId, name: item.dataTypeName }" :label="item.dataTypeName" />
            </el-select>
          </el-form-item>
          <el-form-item label="发送间隔" prop="sendingInterval">
            <el-input v-model="formData.sendingInterval" min="0" type="number" clearable
              @change="handleInput(formData, 'sendingInterval')" placeholder="单位/分钟" />
          </el-form-item>
          <el-form-item label="滤波类型" prop="filterType">
            <el-select class="w100p" filterable clearable v-model="formData.filterType">
              <el-option v-for="(item, index) in filterTypeList" :key="index" :value="item.name" :label="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="滤波值" prop="filterValue">
            <el-input v-model="formData.filterValue" min="0" type="number" clearable placeholder="请输入滤波值"
              @change="handleInput(formData, 'filterValue')" />
          </el-form-item>
          <el-form-item label="上限列表" class="w100p">
            <div>
              <div v-for="(item, index) in formData.nowtopList" :key="index" class="line">
                <el-form-item :prop="'nowtopList.' + index + '.levelName'"
                  :rules="{ required: true, message: '级别名称不能为空', trigger: 'blur' }" class="w100p">
                  <el-input v-model="item.levelName" clearable placeholder="级别名称" />
                </el-form-item>
                <el-form-item :prop="'nowtopList.' + index + '.thresholdValue'"
                  :rules="{ required: true, message: '级别阈值不能为空', trigger: 'blur' }" class="w100p">
                  <el-input v-model="item.thresholdValue" type="number" min="0" clearable placeholder="级别阈值" />
                </el-form-item>
                <el-form-item :prop="'nowtopList.' + index + '.alarmTypeId'"
                  :rules="{ required: true, message: '告警类型不能为空', trigger: 'blur' }" class="w100p">
                  <el-select filterable clearable v-model="item.alarmTypeId" placeholder="告警类型">
                    <el-option v-for="(alarmTypeitem, alarmTypeindex) in alarmTypeList" :key="alarmTypeindex"
                      :label="alarmTypeitem.alarmTypeName" :value="alarmTypeitem.alarmTypeId" />
                  </el-select>
                </el-form-item>
                <div class="line-click" v-show="formData.nowtopList.length > 1" @click="deltopList(index)">
                  <i class="el-icon-minus"></i>
                </div>
                <div class="line-click" v-show="formData.nowtopList.length - 1 === index" @click="addtopList()">
                  <i class="el-icon-plus"></i>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="下限列表" class="w100p">
            <div>
              <div v-for="(item, index) in formData.nowbottomList" :key="index" class="line">
                <el-form-item :prop="'nowbottomList.' + index + '.levelName'"
                  :rules="{ required: true, message: '级别名称不能为空', trigger: 'blur' }" class="w100p">
                  <el-input v-model="item.levelName" clearable placeholder="级别名称" />
                </el-form-item>
                <el-form-item :prop="'nowbottomList.' + index + '.thresholdValue'"
                  :rules="{ required: true, message: '级别阈值不能为空', trigger: 'blur' }" class="w100p">
                  <el-input v-model="item.thresholdValue" clearable type="number" min="0" placeholder="级别阈值" />
                </el-form-item>
                <el-form-item :prop="'nowbottomList.' + index + '.alarmTypeId'"
                  :rules="{ required: true, message: '告警类型不能为空', trigger: 'blur' }" class="w100p">
                  <el-select filterable clearable v-model="item.alarmTypeId" placeholder="告警类型">
                    <el-option v-for="(alarmTypeitem, alarmTypeindex) in alarmTypeList" :key="alarmTypeindex"
                      :label="alarmTypeitem.alarmTypeName" :value="alarmTypeitem.alarmTypeId" />
                  </el-select>
                </el-form-item>
                <div class="line-click" v-show="formData.nowbottomList.length > 1" @click="delbottomList(index)">
                  <i class="el-icon-minus"></i>
                </div>
                <div class="line-click" v-show="formData.nowbottomList.length - 1 === index" @click="addbottomList()">
                  <i class="el-icon-plus"></i>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel('formData')">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>

      <el-dialog :close-on-click-modal='false' :title="'查看告警模板信息'" :visible.sync="dialogeSeeFormVisible" width="50%">
        <el-form ref="formData" :model="formData" label-width="120px" class="demo-ruleForm">
          <el-form-item label="模板名称">
            <el-input v-model="formData.templateName" clearable disabled placeholder="请输入模板名称" />
          </el-form-item>
          <el-form-item label="数据类型">
            <el-select class="w100p" ilterable clearable v-model="nowdataType" disabled value-key="value"
              :placeholder="formData.dataTypeName" @change="addDataType">
              <el-option v-for="(item, index) in dataTypeList" :key="index"
                :value="{ value: item.dataTypeId, name: item.dataTypeName }" :label="item.dataTypeName" />
            </el-select>
          </el-form-item>
          <el-form-item label="发送间隔">
            <el-input v-model="formData.sendingInterval"
              @change="formData.sendingInterval <= 0 ? formData.sendingInterval = '' : ''" disabled clearable
              placeholder="单位/分钟" />
          </el-form-item>
          <el-form-item label="滤波类型">
            <el-select class="w100p" filterable clearable v-model="formData.filterType" disabled>
              <el-option v-for="(item, index) in filterTypeList" :key="index" :value="item.name" :label="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="滤波值">
            <el-input v-model="formData.filterValue"
              @change="formData.filterValue <= 0 ? formData.filterValue = '' : ''" disabled clearable
              placeholder="单位/分钟" />
          </el-form-item>
          <el-form-item label="上限列表">
            <div>
              <div v-for="(item, index) in formData.nowtopList" :key="index" class="line">
                <el-input class="item" v-model="item.levelName" disabled clearable placeholder="级别名称" />
                <el-input class="item" v-model="item.thresholdValue" disabled clearable placeholder="级别阈值" />
                <el-select class="item" filterable clearable disabled v-model="item.alarmTypeId">
                  <el-option v-for="(alarmTypeitem, alarmTypeindex) in alarmTypeList" :key="alarmTypeindex"
                    :label="alarmTypeitem.alarmTypeName" :value="alarmTypeitem.alarmTypeId" />
                </el-select>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="下限列表">
            <div>
              <div v-for="(item, index) in formData.nowbottomList" :key="index" class="line">
                <el-input class="item" v-model="item.levelName" disabled clearable placeholder="级别名称" />
                <el-input class="item" v-model="item.thresholdValue" disabled clearable placeholder="级别阈值" />
                <el-select class="item" filterable clearable v-model="item.alarmTypeId" disabled>
                  <el-option v-for="(alarmTypeitem, alarmTypeindex) in alarmTypeList" :key="alarmTypeindex"
                    :label="alarmTypeitem.alarmTypeName" :value="alarmTypeitem.alarmTypeId" />
                </el-select>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="() => { dialogeSeeFormVisible = false }">取 消</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import BtnSlot from '@/components-production-management/BtnSlot';

import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
import alarmTemplateApi from "@/api/monitoring-alarm/alarm-template-configuration";
import dataTypeApi from "@/api/basic-info-manage/data-type-manage";
import monitoringCategoryApi from "@/api/monitoring-alarm/alarm-category-management";
export default {
  name: "AlarmTemplateConfiguration",
  components: { BtnSlot, Pagination, MainSlot },
  mixins: [mymixin],
  data() {
    return {
      btnList: ['add', 'delete'],
      formData: {
        nowtopList: [{ thresholdType: "UPPERLIMIT" }],
        nowbottomList: [{ thresholdType: "LOWERLIMIT" }]
      },
      rules: {
        templateName: [
          { required: true, message: "请输入告警模板名称", trigger: "blur" },
          {
            LOWERLIMIT: 3,
            UPPERLIMIT: 8,
            message: "长度在 3 到 8 个字符",
            trigger: "blur"
          }
        ],
        sendingInterval: [
          { required: true, message: "请输入发送间隔", trigger: "blur" }
        ],
        filterValue: [
          { required: true, message: "请输入滤波值", trigger: "blur" }
        ],
        filterType: [
          { required: true, message: "请选择滤波类型", trigger: "blur" }
        ],
        dataTypeName: [
          { required: true, message: "请选择数据类型", trigger: "blur" }
        ]
      },
      // 确认删除弹框
      delDialogVisible: false,
      filterTypeList: [
        {
          name: "时间"
        },
        {
          name: "次数"
        }
      ],
      // 数据类别
      nowdataType: {},
      dataTypeList: [],
      // 告警类型下拉数据
      alarmTypeList: [],
      // 搜索内容
      searchList: {},
      // 选中的数据项数组 alarmContactId组成 (此数组最多为一个)
      selectIdList: [],
      dialogFormVisible: false,
      dialogeSeeFormVisible: false,
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    nowChanceStau: {
      handler(val) {
        console.log(val)
        if (val === "add") {
          this.$nextTick(() => {
            this.formData = {
              nowtopList: [{ thresholdType: "UPPERLIMIT" }],
              nowbottomList: [{ thresholdType: "LOWERLIMIT" }]
            }

            this.$refs['formData'].clearValidate()
          })
          this.nowdataType = {};
          this.alarmTypeList = [];
          this.nowtopList = [];
        }
      }
    },
    dialogFormVisible: {
      handler(status) {
        if (!status) {
          this.formData = {}
          this.$refs['formData'].resetFields()
          console.log('重置表单验证')
        }
      }
    }
  },
  created() {
    // 获取表格数据
    this.search();
  },
  mounted() {
    this.getselectlist();
  },
  methods: {
    editData(row) {
      console.log(row)
      this.formData = {}
      for (let key in row) {
        this.$set(this.formData, key, row[key])
      }

      this.nowChanceStau = 'edit'
      this.title = '编辑'
      this.dialogFormVisible = true

    },
    handleInput(data, name) {
      data[name] < 0 && (data[name] = '')
    },
    // 获取表格数据
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize
      };
      alarmTemplateApi.getlist(params).then(res => {
        this.loading = false;
        if (res.errCode !== undefined) {
          this.$message.error("查询失败");
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
      });
    },
    // 获取下拉数据
    getselectlist() {
      // 获取所有数据类型
      dataTypeApi.queryExistence().then(res => {
        this.dataTypeList = res.data;
      });
    },
    // 添加一条上限数据
    addtopList() {
      if (this.nowChanceStau !== "add" && this.nowChanceStau !== "edit") {
        return;
      }
      let addvalue = {
        thresholdType: "UPPERLIMIT",
      };
      this.formData.nowtopList.push(addvalue);
    },
    // 删除一条上限数据
    deltopList(i) {
      if (this.nowChanceStau !== "add" && this.nowChanceStau !== "edit") {
        return;
      }
      this.formData.nowtopList.splice(i, 1);
    },
    // 添加一条下限数据
    addbottomList() {
      if (this.nowChanceStau !== "add" && this.nowChanceStau !== "edit") {
        return;
      }
      let addvalue = {
        thresholdType: "LOWERLIMIT",
      };
      this.formData.nowbottomList.push(addvalue);
    },
    // 添加一条下限数据
    delbottomList(i) {
      if (this.nowChanceStau !== "add" && this.nowChanceStau !== "edit") {
        return;
      }
      this.formData.nowbottomList.splice(i, 1);
    },
    // 将选择的数据类别添加到表单中 --获取告警类型列表
    addDataType(e) {
      if (this.nowChanceStau === "add" || this.nowChanceStau === "edit") {
        this.formData.dataTypeId = e.value;
        this.formData.dataTypeName = e.name;
      }
      monitoringCategoryApi.queryByCondition({
        dataTypeId: e.value,
        homeBaseId: sessionStorage.homeBaseId
      })
        .then(res => {
          let data = res.data;
          this.chancealarmtype(data);
        });
    },
    // 处理数据类型数据
    chancealarmtype(list) {
      let newlist = [];
      if (list === undefined || list === null)
        return this.$message.warning("请先配置告警类型");
      list.forEach((item, index) => {
        newlist.push(item);
      });
      this.alarmTypeList = newlist;
    },
    // 添加
    add() {
      this.canInput = true;
      this.nowChanceStau = "add";
      this.titleText = "添加";
      this.dialogFormVisible = true;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false;
    },
    handleEdit(zhrow) {
      this.formData = {};
      let row = JSON.parse(JSON.stringify(zhrow));
      if (row.alarmTemplateId) {
        this.formData = {
          alarmTemplateId: row.alarmTemplateId,
          templateName: row.templateName,
          sendingInterval: row.sendingInterval,
          filterValue: row.filterValue,
          filterType: row.filterType,
          dataTypeId: row.dataTypeId,
          dataTypeName: row.dataTypeName,
          noticeConfigNo: row.noticeConfigNo
        };
        this.nowdataType = {
          value: row.dataTypeId,
          name: row.dataTypeName
        };
        this.addDataType({ name: row.dataTypeName, value: row.dataTypeId });
        let mainlist = row.alarmTemplateThresholdList;
        this.$set(this.formData, 'nowtopList', []);
        this.$set(this.formData, 'nowbottomList', []);
        // this.formData.nowtopList = [];
        // this.formData.nowbottomList = [];
        if (mainlist !== null) {
          for (let i = 0; i < mainlist.length; i++) {
            if (mainlist[i].thresholdType === "UPPERLIMIT") {
              this.formData.nowtopList.push(mainlist[i]);
            } else if (mainlist[i].thresholdType === "LOWERLIMIT") {
              this.formData.nowbottomList.push(mainlist[i]);
            }
          }
        }

        this.addActive = true;
        this.editActive = true;
        this.saveActive = false;
        this.cancelActive = true;
      }
    },
    handleSelectionChange(list) {
      this.selectIdList = [];
      let notvalue = true;
      this.selectIdList = list.map(item => {
        if (item.alarmTemplateId) {
          return item.alarmTemplateId;
        } else {
          notvalue = false;
          return "";
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        return;
      }
      if (this.selectIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },

    //获取选中Btn
    getBtnEvent(flag) {
      if (flag == 'add') {
        this.add();
      } else if (flag == 'delete') {
        this.delmessage()
      }
    },
    delmessage() {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      })
        .then(() => {
          alarmTemplateApi.dellist(this.selectIdList).then(res => {
            if (res.success) {
              this.search();
              this.$message.success("删除成功");
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });

    },
    handleDelete(data) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      })
        .then(() => {
          alarmTemplateApi.dellist([data.alarmTemplateId]).then(res => {
            if (res.success) {
              this.search();
              this.$message.success("删除成功");
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    closeDialog() {
      this.dialogeSeeFormVisible = false;
      this.dialogFormVisible = false;
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            let editparams = {
              ...this.formData
            };
            editparams.alarmTemplateThresholdList = [...this.formData.nowbottomList, ...this.formData.nowtopList]
            // ---end---
            if (this.nowdataType.length > 0) {
              this.formData.dataTypeName = this.nowdataType.name;
              this.formData.dataTypeId = this.nowdataType.value;
            }
            // 编辑接口
            alarmTemplateApi.editlist(editparams).then(res => {
              if (res.success) {
                this.$message.success("修改成功！");
                this.closeDialog();
                this.search();
              } else {
                this.$message.error(res.message || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let addparams = {
              alarmTemplateThresholdList: [],
              ...this.formData
            };
            addparams.alarmTemplateThresholdList = [...this.formData.nowbottomList, ...this.formData.nowtopList]
            // end

            if (this.nowdataType.length > 0) {
              this.formData.dataTypeName = this.nowdataType.name;
              this.formData.dataTypeId = this.nowdataType.value;
            }
            // ---
            // console.log(addparams)
            alarmTemplateApi.addlist(addparams).then(res => {
              if (res.success) {
                this.$message.success("新增成功！");
                this.closeDialog();
                this.search();
              } else {
                this.$message.error(res.message || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.line {
  width: 100%;
  display: flex;
  flex-wrap: nowrap;
  margin-bottom: 10px;

  .item {
    width: calc(100% / 3);
  }

  .line-click {
    width: 90px;
    height: 30px;
    // background-color: aqua;
    display: flex;
    justify-content: center;
    align-items: center;
    border: snow 1px solid;
    border-radius: 50%;
    margin-bottom: 10px;
    margin-top: 5px;
    margin-left: 5px;
    cursor: pointer;
  }
}

::v-deep .tableSlot {
  height: 100%;
}
</style>
